package com.partsoft.spring.zks;

import java.util.List;

import org.springframework.util.Assert;

public abstract class AbstractListModel<E> implements ListModel<E> {

	private int activePage = 0;
	
	private int pageSize = 20;
	
	private boolean paging = true;
	
	public AbstractListModel() {}
	
	public AbstractListModel(int pageSize, boolean paging) {
		this.pageSize = pageSize;
		this.paging = paging;
	}

	public AbstractListModel(boolean paging) {
		this.paging = paging;
	}

	protected abstract List<E> doGetItems();

	public List<E> getItems() {
		return doGetItems();
	}

	public int getActivePage() {
		if (activePage * getPageSize() > getTotalSize()) {
			activePage = getTotalSize() / getPageSize();
		}
		return activePage;
	}
	
	protected abstract void cleanCaches();

	public void setActivePage(int activePage) {
		this.activePage = activePage;
		cleanCaches();
	}

	public int getPageSize() {
		return pageSize;
	}
	
	public void setPageSize(int pageSize) {
		Assert.isTrue(pageSize > 0, "每页大小必须大于0");
		if (pageSize > 0 && pageSize != this.pageSize) {
			this.pageSize = pageSize;
			cleanCaches();			
		}
	}
	
	protected abstract int doGetTotalSize();

	public int getTotalSize() {
		return doGetTotalSize();
	}

	public boolean isPaging() {
		return paging;
	}
	
	public void refresh() {
		cleanCaches();
	}
	
	public void setPaging(boolean paging) {
		if (this.paging != paging) {
			this.paging = paging;
			cleanCaches();
		}
	}
}
